package com.im.gateway.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.socket.SocketChannel;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Created leijun
 * @Date 2021/9/11 10:16 上午
 */
public class SessionManager {

    private SessionManager() {}

    private static class Singleton {
        private static volatile SessionManager instance = new SessionManager();
    }
    public static SessionManager getInstance () {
        return Singleton.instance;
    }

    private ConcurrentHashMap<Long, SocketChannel> sessions = new ConcurrentHashMap<>();

    private ConcurrentHashMap<String, Long> user2Host = new ConcurrentHashMap<>();
    /**
     * 保存客户端socketChannel
     * @param userId
     * @param socketChannel
     */
    public void addSession(Long userId, SocketChannel socketChannel) {
        String socketChannelId = socketChannel.remoteAddress().getHostName() + ":" + socketChannel.remoteAddress().getPort();
        user2Host.put(socketChannelId, userId);
        sessions.put(userId, socketChannel);
    }

    /**
     * 获取uid
     * @param channelId
     * @return
     */
    public Long getUidByChannelId(String channelId) {
        return user2Host.get(channelId);
    }

    /**
     * 是否已经存在用户客户端
     * @param userId
     * @return
     */
    public Boolean exists(String userId) {
        return this.sessions.contains(userId);
    }

    /**
     * 获取用户客户端socketChannel
     * @param userId
     * @return
     */
    public SocketChannel getSession(Long userId) {
        return this.sessions.get(userId);
    }

    /**
     * 移除客户端
     * @param socketChannel
     */
    public void remove(SocketChannel socketChannel) {
        String socketChannelId = socketChannel.remoteAddress().getHostName() + ":" + socketChannel.remoteAddress().getPort();
        Long userId = user2Host.get(socketChannelId);
        this.sessions.remove(userId);
        this.user2Host.remove(socketChannelId);
    }

    /**
     * 往客户端写入消息
     * @param uid
     * @param msg
     */
    public void writeAndFlush(Long uid, ByteBuf msg) {
        SocketChannel socketChannel = this.sessions.get(uid);
        socketChannel.writeAndFlush(msg);
    }
}
